﻿package vklib 
{
	import flash.events.*;
	/**
	 * ...
	 * @author apisoc@gmail.com
	 */
	internal class ResultBase implements IResult
	{
		protected var handlers:Object = { onSuccess: null, onError: null, onProgress: null };
		
		protected function init(dispatcher:IEventDispatcher):void
		{
			dispatcher.addEventListener(Event.COMPLETE, successHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
			if (handlers.onProgress)
				dispatcher.addEventListener(ProgressEvent.PROGRESS, handlers.onProgress);
		}
		
		public function set onSuccess(f:Function):void { handlers.onSuccess = f; }
		public function set onError(f:Function):void { handlers.onError = f; }
		public function set onProgress(f:Function):void { handlers.onProgress = f; }
		
		public function load():void
		{
			VkApi.debug('ResultBase must be inherited', this);
		}
		
		protected function successHandler(e:Event):void
		{
			e.target.removeEventListener(e.type, successHandler);
			if (handlers.onSuccess)
				handlers.onSuccess(e.target);
		}
		
		protected function errorHandler(e:ErrorEvent):void
		{
			e.target.removeEventListener(e.type, errorHandler);
			if (handlers.onError)
				handlers.onError(e.text);
			else
				VkApi.debug(e.text, e.target);			
		}
	}

}